import queue
import threading
import time
from datetime import datetime


class DelayQueue:
    def __init__(self):
        self.pq = queue.PriorityQueue()
        self.worker_thread = threading.Thread(target=self._monitor, daemon=True)
        self.worker_thread.start()

    def put(self, item):
        end_time_str = item["end_time"]
        end_time = datetime.strptime(end_time_str, "%Y-%m-%d %H:%M:%S")
        timestamp = end_time.timestamp()

        self.pq.put((timestamp, item))
        print(f"已入队: {item}")

    def _monitor(self):
        while True:
            try:
                timestamp, item = self.pq.queue[0]  # 查看队首元素但不出队
                if timestamp <= time.time():
                    # 到达时间，取出处理
                    _, item = self.pq.get()
                    print(f"时间到，已出队: {item}")
                    # 可在此添加额外处理逻辑，如释放资源等
            except IndexError:
                # 队列为空
                pass

            time.sleep(0.5)  # 控制轮询频率


# 测试示例
if __name__ == "__main__":
    dq = DelayQueue()

    # 添加测试数据
    dq.put({"ip": "114.96.199.104", "port": "22420", "end_time": "2025-07-16 17:12:24"})
    dq.put({"ip": "8.8.8.8", "port": "8080", "end_time": "2025-07-16 17:12:00"})
    dq.put({"ip": "1.1.1.1", "port": "3128", "end_time": "2025-07-16 17:11:00"})

    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        print("程序结束")
